package com.shi.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.lettuce.core.ReadFrom;
import org.springframework.boot.autoconfigure.data.redis.LettuceClientConfigurationBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Author 史豪通
 * Date 2024/08/24 11:18
 */
@Configuration
public class RedisConfig {

    // 这个对象只要存放在ioc容器中，redisTemplate对象会自动的调用
    @Bean
    public LettuceClientConfigurationBuilderCustomizer redisClientConfig() {
        /*
         * ReadFrom.REPLICA : 读取数据只从从机读取
         * ReadFrom.REPLICA_PREFERRED : 优先读取从机数据，如果找不到从机，从主机读取
         */
        return clientConfigurationBuilder -> clientConfigurationBuilder.readFrom(ReadFrom.REPLICA_PREFERRED);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        //1.创建
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        System.out.println(template);

        //2.设置key和value的序列化格式
        RedisSerializer<String> keySerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer<Object> valueSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

        ObjectMapper objectMapper = new ObjectMapper();
        //设置jackson在序列化和反序列化中对对象的所有属性进行处理
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        valueSerializer.setObjectMapper(objectMapper);

        template.setKeySerializer(keySerializer);
        template.setValueSerializer(valueSerializer);//String类型的序列化
        template.setHashKeySerializer(valueSerializer);//Hash类型的序列化

        //3.设置连接工厂
        template.setConnectionFactory(factory);

        return template;
    }
}
